import { createApp } from "vue";
import App from "./App.vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import { createPinia } from "pinia";
import router from "@/router";
import { mapTreeToRoute } from "@/utils";
import { useUserStore } from "@/store/userStore";
import cache from "@/utils/cache";
import "@/assets/app.css";
import "nprogress/nprogress.css";
const pinia = createPinia();
const app = createApp(App);
import VueSweetalert2 from "vue-sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";
import Swal from "sweetalert2";
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const isAuth = cache.getCache("isAuth");
  const userInfoLoaded = cache.getCache("userInfoLoaded");
  cache.setCache("userInfoLoaded", false);

  // 检查 token 是否过期
  if (isAuth && userStore.isTokenExpired()) {
    Swal.fire({
      title: "会话过期",
      text: "请重新登录",
      icon: "warning",
    });
    userStore.logout();
    return next("/login");
  }
  // 如果用户未认证，重定向到登录页面
  if (!isAuth && to.path !== "/login") {
    return next("/login");
  }

  // 如果用户已认证且尝试访问登录页面，重定向到主页
  if (isAuth && to.path === "/login") {
    return next("/");
  }

  // 如果用户已认证，确保用户信息已加载
  if (isAuth && !userInfoLoaded) {
    try {
      await userStore.getUserInfo();
      const newRoutes = mapTreeToRoute(userStore.menuTree);
      const existingRoutes = router.getRoutes().map((route) => route.name);

      newRoutes.forEach((route) => {
        if (!existingRoutes.includes(route.name)) {
          router.addRoute("Layout", route);
        }
      });

      cache.setCache("userInfoLoaded", true); // 标记用户信息已加载
      return next(to.fullPath); // 确保导航到目标路径
    } catch (error) {
      console.error("Error loading user info:", error);
      return next("/login");
    }
  }

  // 如果用户已认证且用户信息已加载，直接继续导航
  if (isAuth && userInfoLoaded) {
    return next();
  }

  next();
});
router.afterEach((to, from) => {});
app.use(VueSweetalert2);
app.use(pinia);
app.use(router);
app.use(ElementPlus, { size: "small", zIndex: 3000 });

app.mount("#app");
